/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useCallback } from 'react';
import { connect } from 'dva';
import { Form, Button, Input, Modal } from 'antd';
import { debounce } from 'lodash';
import AddressCascader from '@/components/AddressCascader';
import ZoneSelect from '@/components/_pages/Post/Area/ZoneSelect';
import DownloadBar from '../DownloadBar';
import styles from './style.less';

const FormItem = Form.Item;

const Search = props => {
  const {
    dispatch,
    form,
    loading,
    applyLoading,
    searchType,
    user,
    zyAuditLoading,
    zySubPostStationsLoading,
    current,
    options: { key: platformKey },
  } = props;
  const { getFieldDecorator, validateFields, resetFields } = form;
  const { currentUser = {} } = user;
  const { user_info = {} } = currentUser;
  const { branchId, inn_area_ids = [], area_ids } = user_info;
  const [all, setAll] = useState(false);
  const [iniBranchId, setBranchId] = useState(null); // 初始的用户branchId
  const { branch } = user?.currentUser?.user_info;
  const isYzPlatform = platformKey === 'yz';
  const isZyAccount = platformKey === 'post';
  useEffect(
    () => {
      if (branchId) {
        setBranchId(branchId);
      }
    },
    [branchId],
  );

  const getFormValues = then => {
    validateFields((err, fieldsValue) => {
      const { codeArr } = fieldsValue;
      if (err) return;
      let values = {};
      // branch_id取级联的最后一位
      const branch_id =
        fieldsValue.branch_id && fieldsValue.branch_id.length > 0
          ? [...fieldsValue.branch_id].reverse()[0]
          : iniBranchId;
      const forMatCodeArr = codeArr && codeArr.length > 0 ? [...codeArr][codeArr.length - 1] : '';
      if (searchType == '1') {
        isZyAccount
          ? (values = {
              // 中邮，下属驿站请求参数
              status: 1,
              keyword: fieldsValue.keyword || '',
              branch_id,
              page: 1,
              pageSize: 20,
            })
          : (values = {
              is_district: '0',
              key: '1',
              keyword: fieldsValue.keyword || '',
              code: forMatCodeArr,
              area_id: fieldsValue.area_id,
            });
      } else if (searchType == '2') {
        values = {
          is_district: '1',
          key: '2',
          keyword: fieldsValue.keyword || '',
          code: forMatCodeArr,
        };
      } else if (searchType == '3') {
        isZyAccount // 中邮，待审核请求参数
          ? (values = {
              keyword: fieldsValue.keyword || '',
              branch_id,
              status: 0,
              page: 1,
              pageSize: 20,
            })
          : (values = {
              is_district: '2',
              key: '3',
              keyword: fieldsValue.keyword || '',
              code: forMatCodeArr,
            });
      } else if (searchType == '4') {
        values = {
          is_district: '3',
          key: '4',
          keyword: fieldsValue.keyword || '',
          code: forMatCodeArr,
        };
      } else if (searchType == '5') {
        // 中邮禁用驿站
        values = {
          keyword: fieldsValue.keyword || '',
          branch_id,
          status: 2,
          pageSize: 20,
          page: 1,
        };
      }
      then(values);
    });
  };

  const handleSearchForthe = useCallback(
    debounce(
      e => {
        e.preventDefault();
        let type;
        getFormValues(values => {
          switch (searchType) {
            case '4':
              type = 'area/getApplyList';
              break;
            case '1':
              isZyAccount
                ? (type = 'area/zyGetSubPostStations') // 中邮，下属驿站
                : (type = 'area/subList');
              break;
            case '3':
              isZyAccount
                ? (type = 'area/zyGetSubPostStationsToBeChecked') // 中邮待审核
                : (type = 'area/subList');
              break;
            case '5':
              type = 'area/zyGetSubPostStations'; // 中邮，已禁用驿站
              break;
            default:
              type = 'area/subList';
              break;
          }
          dispatch({
            type,
            payload: values,
          });
          if (values.keyword != '' && !isZyAccount) {
            setAll(true);
          }
        });
      },
      500,
      {
        leading: true,
        trailing: false,
      },
    ),
    [iniBranchId],
  );
  const getExportAllData = () => {
    let data = {};
    getFormValues(values => {
      data = { ...values };
      if (searchType == '4') {
        data.dl = 1;
      } else {
        data.export = 1;
      }
    });
    return data;
  };

  const allSearch = () => {
    getFormValues(values => {
      const type = values.is_district == '3' ? 'area/getApplyList' : 'area/subList';
      dispatch({
        type,
        payload: {
          is_district: values.is_district,
          keyword: '',
          pageNum: current,
        },
        then: () => {},
      });
      resetFields();
      setAll(false);
    });
  };

  const onExport = useCallback(
    debounce(
      () => {
        const { branch_id, keyword } = getExportAllData();
        dispatch({
          type: 'area/zyExport',
          payload: {
            branch_id,
            keyword,
          },
        }).then(({ code, msg = '导出失败！' } = {}) => {
          const content = code > 0 ? msg : '导出数据提交已申请，请至【报表下载】处下载';
          Modal.info({
            title: '温馨提示',
            content,
            centered: true,
          });
        });
      },
      500,
      {
        leading: true,
        trailing: false,
      },
    ),
    [],
  );

  return (
    <div className={styles.mainSearch}>
      <Form onSubmit={handleSearchForthe} className={styles['search-form']} layout="inline">
        {!!(isZyAccount && searchType === '1') && (
          <FormItem>
            {getFieldDecorator('branch_id')(
              <AddressCascader
                level={3}
                type="search"
                width={400}
                companyId={iniBranchId}
                request
              />,
            )}
          </FormItem>
        )}
        {isYzPlatform &&
          searchType === '1' &&
          inn_area_ids.length > 0 && (
            <FormItem>
              {getFieldDecorator('area_id', {
                initialValue: area_ids == '*' ? '0' : [...inn_area_ids].reverse().join(','),
              })(<ZoneSelect type="inn" />)}
            </FormItem>
          )}

        {isYzPlatform &&
          searchType != '4' && (
            <FormItem>
              {getFieldDecorator('codeArr', {
                initialValue: branch.map(i => i.code),
              })(
                <AddressCascader
                  level={4}
                  fieldNames={{ label: 'name', value: 'code' }}
                  width={400}
                  branch={branch}
                  request
                  changeOnSelect
                />,
              )}
            </FormItem>
          )}

        <FormItem>
          {getFieldDecorator('keyword')(
            <Input
              className={styles.searchInput}
              placeholder={
                searchType == '4'
                  ? '请输入手机号码或姓名称查找'
                  : `请输入${isZyAccount ? '中邮' : '快宝'}驿站的注册手机号码、或驿站名称查找`
              }
            />,
          )}
        </FormItem>
        <FormItem>
          <span className={styles.submitButtons}>
            <Button
              type="primary"
              htmlType="submit"
              key="search"
              loading={loading || applyLoading || zySubPostStationsLoading || zyAuditLoading}
              icon="search"
            >
              查询
            </Button>
          </span>
          {all ? (
            <div
              style={{
                marginLeft: '16px',
                display: 'inline-block',
              }}
            >
              <a onClick={allSearch}>返回全部</a>
            </div>
          ) : (
            ''
          )}
        </FormItem>
        {isZyAccount &&
          searchType == 1 && (
            <FormItem>
              <Button type="primary" onClick={onExport}>
                导出
              </Button>
            </FormItem>
          )}
        {isYzPlatform && (
          <FormItem>
            <DownloadBar
              href={
                searchType == '4'
                  ? '/Api/YZ/CourierStation/applyList'
                  : '/Api/YZ/CourierStation/subList'
              }
              nonceKey="code,area_id"
              query={getExportAllData}
            >
              <Button type="primary" icon="upload">
                导出
              </Button>
            </DownloadBar>
          </FormItem>
        )}
      </Form>
    </div>
  );
};

export default connect(({ loading, area, user, setting }) => ({
  area,
  user,
  loading: loading.effects['area/subList'],
  applyLoading: loading.effects['area/getApplyList'],
  zySubPostStationsLoading: loading.effects['area/zyGetSubPostStations'],
  zyAuditLoading: loading.effects['area/zyGetSubPostStationsToBeChecked'],
  ...setting,
}))(Form.create()(Search));
